const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    trim: true,
    minlength: 2,
    maxlength: 20
  },
  nickname: {
    type: String,
    trim: true,
    maxlength: 20
  },
  avatar: {
    type: String,
    default: ''
  },
  isOnline: {
    type: Boolean,
    default: false
  },
  lastSeen: {
    type: Date,
    default: Date.now
  },
  totalWins: {
    type: Number,
    default: 0
  },
  totalLosses: {
    type: Number,
    default: 0
  },
  totalEarnings: {
    type: Number,
    default: 0
  },
  email: {
    type: String,
    required: false,
    unique: true,
    sparse: true,
    lowercase: true,
    set: function(email) {
      return email === '' ? undefined : email;
    }
  },
  password: {
    type: String,
    required: false,
    minlength: 6,
    set: function(password) {
      return password === '' ? undefined : password;
    }
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  wechatOpenId: {
    type: String,
    unique: true,
    sparse: true
  }
}, {
  timestamps: true
});

// 密码加密
userSchema.pre('save', async function(next) {
  if (!this.isModified('password') || !this.password) return next();
  
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

// 密码验证
userSchema.methods.comparePassword = async function(candidatePassword) {
  if (!this.password) return false;
  return await bcrypt.compare(candidatePassword, this.password);
};

// 生成随机用户名
userSchema.statics.generateRandomUsername = function() {
  
  const nouns = [
    '玩家', '高手', '大师', '新手', '专家', '达人', '王者', '传奇',
    '英雄', '战士', '法师', '射手', '刺客', '坦克', '辅助', '召唤',
    '冠军', '明星', '偶像', '领袖', '导师', '教练', '队长', '队员'
  ];
  const numbers = Math.floor(Math.random() * 999) + 1;
  const noun = nouns[Math.floor(Math.random() * nouns.length)];
  
  return `${noun}${numbers}`;
};

// 检查用户名是否可用
userSchema.statics.isUsernameAvailable = async function(username) {
  const existingUser = await this.findOne({ username });
  return !existingUser;
};

module.exports = mongoose.model('User', userSchema); 